/*
 *   Copyright 2012-present OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

// Packages
import axios from 'axios';
import fileDownload from 'js-file-download';
import qs from 'qs';
import $ from 'jquery';

// Utils
import { Saiku, Settings } from '../utils';

// Constants
const QUERY_URL = 'api/query';
const EXPORT_FILE_TYPE = 'pdf';
const EXPORT_FILE_FORMATTER = 'flattened';

// Axios Cancellation
const CancelToken = axios.CancelToken;
let axiosCancelRequest;

class QueryService {
  static async exportFile(
    uuid,
    fileType = EXPORT_FILE_TYPE,
    formatter = EXPORT_FILE_FORMATTER
  ) {
    const url = `${Settings.REST_URL}/${QUERY_URL}/${uuid}/export/${fileType}/${formatter}`;
    let fileName =
      fileType === 'xls' ? `saiku-export.xlsx` : `saiku-export.${fileType}`;
    let response;

    try {
      response = await axios.get(url, {
        responseType: 'blob',
        cancelToken: new CancelToken(function executor(c) {
          // An executor function receives a cancel function as a parameter
          axiosCancelRequest = c;
        })
      });
    } catch (error) {
      Saiku.axiosHandleErrors(
        'services → QueryService.js → exportFile()',
        error
      );
    }

    if (response.status === 200) {
      fileName = response.headers['content-disposition'].split(
        'filename = '
      )[1];
    }

    fileDownload(response.data, fileName);

    return response;
  }

  static async exportChart(fileType = EXPORT_FILE_TYPE) {
    const url = `${Settings.REST_URL}/${QUERY_URL}/${window.escape(
      '../export/saiku/chart'
    )}`;
    const rep = '<svg xmlns="http://www.w3.org/2000/svg" ';
    let svgContent = new XMLSerializer().serializeToString(
      $('.sku-canvas-wrapper').find('svg')[0]
    );
    let fileName = `saiku-export.${fileType}`;
    let response;

    if (svgContent.substr(0, rep.length) !== rep) {
      svgContent = svgContent.replace('<svg ', rep);
    }

    svgContent = `<!DOCTYPE svg [<!ENTITY nbsp "&#160;">]>${svgContent}`;

    const data = {
      type: fileType,
      svg: svgContent,
      name: ''
    };

    try {
      response = await axios.post(url, qs.stringify(data), {
        headers: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        responseType: 'blob',
        cancelToken: new CancelToken(function executor(c) {
          // An executor function receives a cancel function as a parameter
          axiosCancelRequest = c;
        })
      });
    } catch (error) {
      Saiku.axiosHandleErrors(
        'services → QueryService.js → exportChart()',
        error
      );
    }

    if (response.status === 200) {
      fileName = response.headers['content-disposition'].split(
        'filename = '
      )[1];
    }

    fileDownload(response.data, fileName);

    return response;
  }

  static cancelRequest() {
    // Cancel the axios request
    // Reference: https://github.com/axios/axios#cancellation
    axiosCancelRequest();
  }
}

export default QueryService;
